package com.example.im.ui.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.callback.OnClickRoomListener
import com.example.im.common.Constants
import com.example.im.common.ImApplication
import com.example.im.entity.FriendOrRoom
import com.example.im.ui.adapter.RoomInviteAdapter
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.utils.JsonUtils
import com.example.im.utils.LogUtils
import kotlinx.android.synthetic.main.fragment_room_invite.*

class RoomInviteFragment : AbstractBaseFragment<BasePresenter<*>>(), View.OnClickListener {


    var adapter: RoomInviteAdapter? = null

    private var mOnClickRoomListener: OnClickRoomListener? = null

    companion object {
        fun newInstance(owners: ArrayList<FriendOrRoom>): RoomInviteFragment {
            val bundle = Bundle()
            bundle.putSerializable(Constants.BUNDLE_T0_ROOM_DATA, owners)
            val fragment = RoomInviteFragment()
            fragment.arguments = bundle
            return fragment
        }

        fun newInstance(): RoomInviteFragment {
            return RoomInviteFragment()
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnClickRoomListener = context as OnClickRoomListener
    }

    override val layoutId: Int
        get() = R.layout.fragment_room_invite

    override fun initView() {


        adapter = RoomInviteAdapter(activity!!, mutableListOf())
        recycler_view.layoutManager = LinearLayoutManager(activity!!)
        recycler_view.adapter = adapter

        tv_room_invite.setOnClickListener(this)

        val friends = ImApplication.appDatabase()
            .friendOrRoomDao().selectFriends() ?: return
        val friendNews = mutableListOf<FriendOrRoom>()
        friends.forEach { f ->
            val isEqual = getOwners().none { o ->
                o.account == f.account
            }
            if (!isEqual) {
                f.sub = -1
            }
            friendNews.add(f)
        }
        adapter!!.addData(friendNews)
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onClick(v: View?) {
        mOnClickRoomListener!!.onClickInvite(v!!, adapter!!.getSelectedItem())
    }

    private fun getOwners(): MutableList<FriendOrRoom> {
        if (arguments == null)
            return ArrayList()
        val arrayList =
            (arguments!!.getSerializable(Constants.BUNDLE_T0_ROOM_DATA) ?: return mutableListOf())
                    as ArrayList<*>
        val owners = mutableListOf<FriendOrRoom>()
        arrayList.forEach {
            owners.add(it as FriendOrRoom)
        }
        return owners
    }
}